<script setup lang="ts">
import { useStoreDict } from '@/store/modules/dict'
import { useGetInfoPropty, useInfoAdd, useInfoDel } from '@fl/api/man-api/pricing-tool'
import { cloneDeep, isNull } from 'lodash-es'
import NP from 'number-precision'
import { computed, ref, toRefs } from 'vue'
import { useRoute } from 'vue-router'

const props = withDefaults(defineProps<{
    data?: any
    limit?: number
}>(), {
    limit: 20,
})

const emits = defineEmits(['onSuccess'])

const { query } = useRoute()

const { dicts } = useStoreDict()

const { data, limit } = toRefs(props)
const tableRef = ref()
const visible = defineModel<boolean>()

const params = computed(() => (query?.calcCategoryId ?? ''))
const { data: colItem } = useGetInfoPropty(params)

const tableData = ref<any>([])

const { mutate } = useInfoDel()
function doDel({ $index, row }) {
    if (row?.id) {
        ElMessageBox.confirm('该操作将永久删除，是否继续?', '提示', { type: 'warning' })
            .then(() => {
                mutate(row.id, {
                    onSuccess: () => {
                        ElMessage({ message: '操作成功', type: 'success' })
                        emits('onSuccess')
                    },
                })
            })
    }

    tableData.value.splice($index, 1)
}

function getReqired() {
    const target: any = []
    colItem.value.forEach((v: any) => {
        if (v.isCalc) {
            target.push(v.title)
        }
    })
    return target
}

function getRow() {
    const target = {}
    colItem.value.forEach((v: any) => {
        target[v.title] = ''
    })
    return target
}

function doAdd() {
    const len = tableData.value.length
    if (len >= limit.value) {
        ElMessage.error(`最多添加${limit.value}条数据！`)
        return
    }

    let isNext = true
    // 校验上条数据 是否填写完整
    if (len) {
        const target = tableData.value[len - 1]
        getReqired().forEach((key: any) => {
            if (!target[key] && target[key] !== 0) {
                isNext = false
            }
        })
    }

    if (!isNext) {
        ElMessage.error(`请填写第${len}条数据必填项`)
        return
    }

    tableData.value.push(getRow())

    if (tableData.value.length > 5) {
        nextTick(() => {
            tableRef.value.setScrollTop(len * 300)
        })
    }
}

function cancel() {
    visible.value = false
}

const { mutate: mutateAdd } = useInfoAdd()
function save() {
    const categoryData = cloneDeep(tableData.value)
    if (!categoryData.length) {
        ElMessage.error(`请添加属性！`)
        return
    }

    let isEnpty = false
    tableData.value.forEach((item: any) => {
        isEnpty = getReqired().some((v: any) => !item[v] && item[v] !== 0)
    })
    if (isEnpty) {
        ElMessage.error(`请填写必填项`)
        return
    }

    mutateAdd({ calcCategoryId: params.value, categoryData }, {
        onSuccess: () => {
            ElMessage({ message: '操作成功', type: 'success' })
            cancel()

            emits('onSuccess')
        },
    })
}

function init() {
    if (data.value) {
        const target = cloneDeep(data.value)
        tableData.value.push(target)
    }
}
init()
</script>

<template>
    <el-dialog v-model="visible"
               :title="`${data?.id ? '编辑' : '新增'}属性`"
               close-on-press-escape
               @cancel="cancel"
               @closed="cancel"
    >
        <el-table ref="tableRef"
                  :data="tableData"
                  stripe
                  height="300"
        >
            <el-table-column fixed
                             label="序号"
                             type="index"
                             width="60"
            />

            <template v-for="(col, index) in colItem"
                      :key="index"
            >
                <el-table-column v-if="col.type === 2"
                                 :label="col.title"
                                 width="120"
                >
                    <template v-if="col.isCalc"
                              #header
                    >
                        <span><span class="mr-5 c-red">*</span>{{ col.title }}</span>
                    </template>

                    <template #default="scope">
                        <el-select v-model="scope.row[col.title]">
                            <el-option v-for="item in dicts.jc_zjgj_unit"
                                       :key="item.value"
                                       :label="item.label"
                                       :value="item.value"
                            />
                        </el-select>
                    </template>
                </el-table-column>

                <el-table-column v-else-if="col.type === 1"
                                 :label="col.title"
                                 width="180"
                >
                    <template v-if="col.isCalc"
                              #header
                    >
                        <span><span class="mr-5 c-red">*</span>{{ col.title }}</span>
                    </template>

                    <template #default="scope">
                        <el-input-number v-model="scope.row[col.title]"
                                         :step="0.0001"
                                         placeholder="请输入"
                                         :min="0"
                                         :max="999999"
                                         controls-position="right"
                                         @blur="() => {
                                             scope.row[col.title] = isNull(scope.row[col.title]) ? scope.row[col.title] : NP.round(scope.row[col.title], 4)
                                         }"
                        />
                    </template>
                </el-table-column>

                <el-table-column v-else
                                 :label="col.title"
                                 width="150"
                >
                    <template v-if="col.isCalc"
                              #header
                    >
                        <span><span class="mr-5 c-red">*</span>{{ col.title }}</span>
                    </template>

                    <template #default="scope">
                        <el-input v-model="scope.row[col.title]"
                                  maxlength="20"
                                  placeholder="请输入"
                                  clearable
                        />
                    </template>
                </el-table-column>
            </template>

            <el-table-column label="操作"
                             fixed="right"
            >
                <template #default="scope">
                    <el-button link
                               type="primary"
                               @click="doDel(scope)"
                    >
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-button class="mt-20"
                   type="primary"
                   plain
                   @click="doAdd"
        >
            + 新增属性
        </el-button>

        <template #footer>
            <div class="text-center w-full">
                <el-button @click="cancel">
                    取消
                </el-button>

                <el-button type="primary"
                           @click="save"
                >
                    保存
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style scoped lang="scss"></style>
